<script setup lang="ts">
import { ref, reactive, h } from "vue";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import { getOptimizedAssetQuery, exportComplianceAssets } from "../servers";
import { ElMessage, ElTag, ElLink, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";

defineProps<{
  task?: string;
}>();

const router = useRouter();

const searchFormRef = ref<DynamicFormInstance>();
const searchFormData = ref<{
  ip?: string;
  status?: string;
  department?: string;
  contact_person?: string;
  has_vulnerability?: boolean;
}>({});

const searchFormConfig = [
  {
    key: "ip",
    name: "IP地址",
    type: "input" as const,
    span: 8,
  },
  {
    key: "status",
    name: "合规状态",
    type: "select" as const,
    span: 8,
    options: [
      { label: "一致", value: "consistent" },
      { label: "未报备", value: "unreported" },
      { label: "可疑", value: "suspected" },
      { label: "未知", value: "未知" },
    ],
  },
  {
    key: "department",
    name: "部门",
    type: "input" as const,
    span: 8,
  },
  {
    key: "contact_person",
    name: "联系人",
    type: "input" as const,
    span: 8,
  },
  {
    key: "has_vulnerability",
    name: "漏洞状态",
    type: "select" as const,
    span: 8,
    options: [
      { label: "存在漏洞", value: true },
      { label: "无漏洞", value: false },
    ],
  },
];

const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const assetList = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const vulnerabilityDialogData = ref<any>({});

const columns = ref<TableColumn[]>([
  {
    label: "IP地址",
    prop: "ip",
    minWidth: 140,
    slot: "ip",
  },
  {
    label: "端口范围",
    prop: "port_ranges",
    minWidth: 150,
  },
  {
    label: "联系人",
    prop: "contact_person",
    minWidth: 100,
  },
  {
    label: "部门",
    prop: "department",
    minWidth: 200,
    slot: "department",
  },
  {
    label: "合规状态",
    prop: "status",
    minWidth: 100,
    render: (row: any) => {
      const statusMap: Record<string, { text: string; type: string }> = {
        consistent: { text: "一致", type: "success" },
        unreported: { text: "未报备", type: "warning" },
        suspected: { text: "可疑", type: "danger" },
        未知: { text: "未知", type: "info" },
      };
      const status = statusMap[row.status] || {
        text: row.status,
        type: "info",
      };
      return h(ElTag, { type: status.type as any }, () => status.text);
    },
  },
  {
    label: "差异状态",
    prop: "diff_status",
    minWidth: 100,
    render: (row: any) => {
      const statusMap: Record<string, { text: string; type: string }> = {
        closed_port: { text: "关闭端口", type: "warning" },
        new_port: { text: "新增端口", type: "danger" },
        service_diff: { text: "服务差异", type: "warning" },
        正常: { text: "正常", type: "success" },
      };
      const status = statusMap[row.diff_status] || {
        text: row.diff_status,
        type: "info",
      };
      return h(ElTag, { type: status.type as any }, () => status.text);
    },
  },
  {
    label: "高危状态",
    prop: "high_risk_status",
    minWidth: 100,
    render: (row: any) => {
      const status = row.high_risk_status === "存在" ? "danger" : "success";
      return h(ElTag, { type: status as any }, () => row.high_risk_status);
    },
  },
  {
    label: "漏洞信息",
    prop: "vulnerability_info",
    minWidth: 200,
    render: (row: any) => {
      if (!row.vulnerability_info) {
        return h("span", { style: "color: #909399" }, "无");
      }
      const info = row.vulnerability_info;
      const counts = [];
      if (info.has_critical) counts.push(`严重: ${info.critical_count}`);
      if (info.has_high) counts.push(`高危: ${info.high_count}`);
      if (info.has_medium) counts.push(`中危: ${info.medium_count}`);

      return h(
        "div",
        {
          style: "cursor: pointer; color: #409eff; text-decoration: underline;",
          onClick: () => handleViewVulnerability(row.vulnerability_info),
        },
        counts.join(" | ") || "查看详情"
      );
    },
  },
]);

// 获取资产列表
const getAssetList = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      per_page: pagination.pageSize,
    };

    // 添加搜索条件
    if (searchFormData.value.ip) params.ip = searchFormData.value.ip;
    if (searchFormData.value.status)
      params.status = searchFormData.value.status;
    if (searchFormData.value.department)
      params.department = searchFormData.value.department;
    if (searchFormData.value.contact_person)
      params.contact_person = searchFormData.value.contact_person;
    if (searchFormData.value.has_vulnerability !== undefined) {
      params.has_vulnerability = searchFormData.value.has_vulnerability;
    }

    const { data } = await getOptimizedAssetQuery(params);
    if (data && data.results) {
      assetList.value = data.results;
      pagination.total = data.total || 0;
    }
  } catch (error) {
    console.error("获取资产列表失败:", error);
    ElMessage.error("获取资产列表失败");
  } finally {
    loading.value = false;
  }
};

// 查看漏洞详情
const handleViewVulnerability = (vulInfo: any) => {
  vulnerabilityDialogData.value = {
    漏洞统计: {
      严重漏洞数量: vulInfo.critical_count || 0,
      高危漏洞数量: vulInfo.high_count || 0,
      中危漏洞数量: vulInfo.medium_count || 0,
      总漏洞数量: vulInfo.total_count || 0,
    },
    漏洞状态: {
      是否存在严重漏洞: vulInfo.has_critical ? "是" : "否",
      是否存在高危漏洞: vulInfo.has_high ? "是" : "否",
      是否存在中危漏洞: vulInfo.has_medium ? "是" : "否",
    },
  };
  dialogVisible.value = true;
};

const handleSearch = (value: any) => {
  searchFormData.value = { ...value };
  pagination.currentPage = 1;
  getAssetList();
};

const handleReset = () => {
  searchFormRef.value?.resetFields();
  searchFormData.value = {};
  pagination.currentPage = 1;
  getAssetList();
};

const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  getAssetList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  getAssetList();
};

// 解析部门层级
const parseDepartment = (department: any) => {
  if (!department || typeof department !== "string") {
    return [];
  }
  return department.split("/").filter(Boolean);
};

// 处理IP点击
const handleIpClick = (ip: string) => {
  router.push({
    path: "/risk-disposal/ip-detail",
    query: { ip },
  });
};

// 导出功能
const handleExport = async () => {
  try {
    await ElMessageBox.confirm(
      "确定要导出合规资产数据吗？导出可能需要一些时间，请耐心等待。",
      "确认导出",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
      }
    );

    ElMessage.info("正在生成Excel文件，请稍候...");

    const params: any = {
      ip: searchFormData.value.ip,
      owner: searchFormData.value.contact_person,
      department: searchFormData.value.department,
      severity_min: undefined,
      include_library: false,
      mask_sensitive: true,
      async: false,
    };

    // 移除空值参数
    Object.keys(params).forEach((key) => {
      if (params[key] === undefined || params[key] === "") {
        delete params[key];
      }
    });

    const blob = await exportComplianceAssets(params);

    // 从响应头获取文件名或生成默认文件名
    const timestamp = new Date()
      .toISOString()
      .replace(/[-:]/g, "")
      .split(".")[0];
    const filename = `netmanager_export_${timestamp}.xlsx`;

    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);

    ElMessage.success("导出成功！");
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("导出失败:", error);
      ElMessage.error("导出失败，请稍后重试");
    }
  }
};

// 初始化
getAssetList();
</script>

<template>
  <div>
    <el-card shadow="never">
      <div class="search-form-container">
        <DynamicForm
          ref="searchFormRef"
          v-model="searchFormData"
          :form-config="searchFormConfig"
          :gutter="16"
          label-width="90px"
          type="search"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </el-card>

    <el-card shadow="never" class="mt-4">
      <DynamicTable
        :data="assetList"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        :show-toolbar="true"
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
      >
        <template #toolbar-left>
          <el-button type="primary" @click="handleExport">导出</el-button>
        </template>

        <!-- IP地址列插槽 -->
        <template #ip="{ row }">
          <el-link
            type="primary"
            :underline="false"
            style="cursor: pointer"
            @click="handleIpClick(row.ip)"
          >
            {{ row.ip }}
          </el-link>
        </template>

        <!-- 部门列插槽 -->
        <template #department="{ row }">
          <div v-if="row.department" class="department-item">
            <div class="dept-path">
              <span
                v-for="(part, partIndex) in parseDepartment(row.department)"
                :key="partIndex"
                class="dept-level"
                :class="{
                  'dept-level-last':
                    partIndex === parseDepartment(row.department).length - 1,
                }"
              >
                {{ part }}
              </span>
            </div>
          </div>
          <span v-else style="color: #909399">-</span>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 漏洞详情弹窗 -->
    <el-dialog v-model="dialogVisible" title="漏洞详细信息" width="600px">
      <div class="detail-container">
        <div
          class="detail-section"
          v-for="(section, title) in vulnerabilityDialogData"
          :key="title"
        >
          <h3 class="section-title">{{ title }}</h3>
          <div class="info-grid">
            <div class="info-item" v-for="(value, key) in section" :key="key">
              <label class="info-label">{{ key }}:</label>
              <span class="info-value">{{ value }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-card__header) {
}

.search-form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.mt-4 {
  margin-top: 16px;
}

// 详情对话框样式
.detail-container {
  max-height: 500px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e4e7ed;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  padding: 10px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #409eff;
}

.info-label {
  font-weight: 600;
  color: #606266;
  min-width: 100px;
  margin-right: 8px;
  flex-shrink: 0;
}

.info-value {
  color: #303133;
  word-break: break-word;
  flex: 1;
}

// 部门层级样式
.department-item {
  padding: 6px 8px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #409eff;
  transition: all 0.2s ease;
}

.department-item:hover {
  background: #e6f7ff;
  border-left-color: #1890ff;
}

.dept-path {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 4px;
}

.dept-level {
  font-size: 12px;
  color: #606266;
  padding: 2px 4px;
  border-radius: 3px;
  background: #fff;
  border: 1px solid #e4e7ed;
  transition: all 0.2s ease;
}

.dept-level-last {
  color: #409eff;
  font-weight: 500;
  background: #e6f7ff;
  border-color: #91d5ff;
}

// 响应式设计
@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .info-label {
    margin-bottom: 4px;
  }
}
</style>
